(function() {
  var geostack = [];
  var totalPage = 0;
  var searchNews = null;
  var searchWe = null;
  var searchStack = [];
  var searchResult = [];
  var keyword = "春运";
  var regions = [];

  function $(id) {
    return document.getElementById(id);
  }
  function $$(name){
   return document.getElementsByTagName(name);
  }
  function $n(tag, className, prt, attributes){
    var el = document.createElement(tag);
    el.className = className || "";
    if (prt) prt.appendChild(el);
    if (attributes){
      for (var nm in attributes){
        el.setAttribute(nm, attributes[nm])
      }
    }
    return el;
  }
 
  function $h(url){
    var head = $$("head")[0] || $n("head", document.body.parentNode);
    $n("script", null, head, { "src": url });
  }
  function autoScroll(node){
    var parent = node.parentNode.parentNode;
    var offset = node.offsetHeight;
    var parentTop = parent.scrollTop;
    var nodeTop = node.offsetTop - node.parentNode.offsetTop;
    var curOffset = nodeTop - parentTop;
    if (curOffset > parent.offsetHeight) {  //scroll bar down
      parent.scrollTop = parent.scrollTop + (curOffset - parent.clientHeight + offset);
    } else if (curOffset < 0) {  //scroll bar up
      parent.scrollTop = parent.scrollTop - Math.abs(curOffset);
    }
  }
  
  
  
  function _un(str){
    return str.replace(/&([^;]+);/g, function(s, entity){
      switch (entity) {
        case 'amp':
          return '&';
        case 'lt':
          return '<';
        case 'gt':
          return '>';
        case 'quot':
          return '"';
        default:
          if (entity.charAt(0) == '#') {
            var n = Number('0' + entity.substr(1));
            if (!isNaN(n)) {
              return String.fromCharCode(n);
            }
          }
          return s;
      }
    });
  };
  
  function makeShareButton(){
    if (!google || !google.share || !google.share.SharingWidget) {
      //GLog.write("failure");
      return;
    }
    // TODO: refine the text here !!!!
    var g = {
      'linkText': '将此地图分享给朋友',
      'url': 'http://ditu.google.cn/maps/mpl?moduleurl=http://www.google.cn/mapfiles/mapplets/ditu/chunyun/chunyun-map.xml',
      'title': '地图--春运信息快速查询',
      'image': 'http://ditu.google.cn/intl/zh-CN_cn/images/maps_logo_beta_small.png',
      'subject_template': _un('{FROM}邀请您一起去谷歌地图看看春运信息'),
      'comments_template': _un('春运信息好分散啊？不用费心了，您的朋友（{FROM}）在谷歌地图上已经找到了一个搜集很详细的地方，来看看吧 :) '),
      'description': '春运信息好分散啊？不用费心了，我们已经在地图上都给你找出来了，快来看看吧。',
      'buttonStyle': 'link',
      'tabs': 'email,email',
      'popup': true,
      'nopreview': true,
      'noaddto': true,
      'noThumbnail': true
    };
    new google.share.SharingWidget("share_button", g);
  };
  
  var rpcProxy = (function(){
    // Private member
    var backend_url = "http://dituapps.appspot.com/chunyun";

    var msgBoard = $("listContainer");
    var msgFlag = 0;
    var msgCounter = 0;
    var msgTimeId = null;
    function getParamStr(paramObj){
      var paramArray = [];
      for (var i in paramObj) {
        if (i != "toJSONString" && paramObj[i] != null) {
          var paramToken = i + '=' + paramObj[i];
          paramArray.push(paramToken);
        }
      }
      return paramArray.join("&");
    }
    function request(param, callBackName){
      var paramStr = getParamStr(param);
      var url = backend_url + "?" + paramStr + "&random=" + Math.random();
      url += '&callback=' + callBackName;
      var api = param['api'];
      var scriptTag = document.createElement('script');
      scriptTag.setAttribute('type', 'text/javascript');
      scriptTag.setAttribute('charset', 'utf-8');
      scriptTag.setAttribute('id', 'jsonpScriptTag' + api);
      scriptTag.setAttribute('src', url);
      var oldTag = document.getElementById('jsonpScriptTag' + api);
      var head = document.getElementsByTagName('head')[0];
      if (oldTag) {
        head.removeChild(oldTag);
      }
      head.appendChild(scriptTag);
//       var api = param.api;
//       $h(api+"Sample.js");
//       GLog.write(url);
    }
    function openMsgBoard(msg){
      msg = "<div style='text-align:center;padding:10px;font-size:15px;font-weight:bold;height:100px;line-height:100px;color:red;'>数据加载中...</div>";
      msgBoard.innerHTML = msg;
    }
    
    function closeMsgBoard(){
      
    }
    
    return { // Public members
      getOptions: function(){
        openMsgBoard("数据加载中...");
        var param = {
          api: 'options'
        }
        request(param, 'ChunyunMap.callback_options');
      },
      getWeather: function(page, region){
        if(!page) {
          page = 0;
        }
        openMsgBoard("数据加载中...");
        var param = {
          api: 'weather',
          page: page,
          region: region
        }
        request(param, 'ChunyunMap.callback_weather');
      },
      getSearch:function(regionId, categoryId, date, pageNo){
        $("listContainer").innerHTML = "";
        openMsgBoard("数据加载中...");
        
        var param = {
          api: 'search',
          region : regionId,
          date : date,
          category : categoryId,
          page : pageNo
        }
        if($("viewafter").checked) {
          param["inc"] = 1;
        }
        request(param, 'ChunyunMap.callback_search');
      },
      getSearchAll:function(key, page){
        openMsgBoard("数据加载中...");
        var param = {
          api: 'searchAll',
          key : key,
          page : page
        }
        request(param, 'ChunyunMap.callback_search');
      },
      setWGeo: function(name, latlng){
        var param = {
          api: 'wgeocode',
          name: name,
          latlng: latlng
        };
        request(param, "abc");
      },
      setGeo: function(name, latlng){
        var param = {
          api: 'geocode',
          name: name,
          latlng: latlng
        };
        request(param, "abc");
      },
      getOptionsCallback: function(options){
        mgr.initOptions(options);
        closeMsgBoard();
      },
      getSearchCallback : function(result){
        mgr.importResult(result);
        closeMsgBoard();
      },
      getWeatherCallback: function(result){
        mgr.importWeather(result);
        closeMsgBoard();
      }
    }
  })();
  
  
  var mgr = (function(){
    var map = null;
    var geocoder = new GClientGeocoder();
    var dom = {
      region : $("region"),
      category : $("category"),
      date : $("date"),
      container : $("listContainer"),
      page : $("pageList")
    }
    var cur = {
      region : null,
      category : null,
      date : null,
      page : null
    };
    var cached = {
      region : null,
      category : null,
      latlng: {},
      points : []
    }
    function resizeMap(){
      if(cached.points.length == 1) {
        map.panTo(cached.points[0]);
        return;
      }
      var bounds = new GLatLngBounds();
      for(var i = 0, point; point = cached.points[i]; i++){
        bounds.extend(point);
      }
      map.getBoundsZoomLevelAsync(bounds, function(zoom){
        map.setCenter(bounds.getCenter(), zoom);
      })
      
    }
    
    function addNode(pos){
      var node = $n("p", "list-entry", dom.container);
      node.innerHTML = pos["label"];
      return node;
    }

    function addWNode(title, icon){
      var node = $n("p", "list-entry", dom.container);
      node.innerHTML = '<img style="vertical-align:middle;margin-right:5px;" src="' + icon + '"></img>' + title;
      return node;
    }

    function addWMarker(pos,iconurl){
      var icon = new GIcon();
      icon.image = iconurl;
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 32);
      icon.infoWindowAnchor = new GPoint(16, 2);
      var marker = new GMarker(pos, {icon:icon});
      map.addOverlay(marker);
      cached.points.push(pos);
      return marker;
    }


    function addWListener(marker, node){
      GEvent.addListener(marker, "click", GEvent.callbackArgs(this, openWInfoWindow, node.city));
      GEvent.addListener(marker, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node));
      GEvent.addListener(marker, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node));
      GEvent.addDomListener(node, "click", GEvent.callbackArgs(this, openWInfoWindow, node.city));
      GEvent.addDomListener(node, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node));
      GEvent.addDomListener(node, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node));
    }
    function addMarker(pos, iconurl){
      var icon = new GIcon();
      icon.image = iconurl;
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 16);
      icon.infoWindowAnchor = new GPoint(12, 16);
      var point = new GLatLng(parseFloat(pos.latlng[0]), parseFloat(pos.latlng[1]));
      var marker = new GMarker(point, { title:pos["label"], icon: icon});
      marker.point = point;
      map.addOverlay(marker);
      cached.points.push(point);
      return marker;
    }
    function addListener(node, marker){
      var pos = node.pos;
      GEvent.addListener(marker, "click", GEvent.callbackArgs(this, openInfoWindow, marker, pos));
      GEvent.addListener(marker, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node, pos));
      GEvent.addListener(marker, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node, pos));
      GEvent.addDomListener(node, "click", GEvent.callbackArgs(this, openInfoWindow, marker, pos));
      GEvent.addDomListener(node, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node, pos));
      GEvent.addDomListener(node, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node, pos));
    }
    function highlightPos(marker, node, pos){
      node.className = "list-entry-highlight";
      /*if(!map.getBounds().contains(marker.point)){
        map.panTo(marker.point);
      }*/
//      autoScroll(node);
    }
    function unhighlightPos(marker, node, pos){
      node.className = "list-entry";
    }
    function openWInfoWindow(data){
      var title = data.city + "天气情况";
      var htmlcur = '<div style="width:470px">' + data.info;
      var search = 'http://www.google.cn/search?hl=zh-CN&q=' + data.city + ' + 天气';
      var search2 = 'http://news.google.cn/news?hl=zh-CN&q=' + data.city + ' + 天气';
      htmlcur += '<div style="text-align:right;font-size:12px;"><a href="' + search + '" target="_blank">详情</a> <a href="' + search2 + '" target="_blank">相关资讯</a></div></div>'
      var latlng = new GLatLng(data.lat, data.lng);
      map.openInfoWindowHtml(latlng, htmlcur);
    }
    function openInfoWindow(marker, pos){
      var rs = "";
      var titleHTML = "<a style='margin:0;font-size:15px;font-weight:bold;margin-right:10px;' target='_blank' href='http://www.google.cn/search?q=" + pos["label"] + "'>"+pos["label"]+"</a>";
      if(pos.cata == "ROAD") {
        var re = /^(.*)(省|自治区)/;
        rs = re.exec(pos.region);
        if(rs == null) {
          re = /^(.*)市/;
          rs = re.exec(pos.region);
        }
        rs = rs[0];
        titleHTML = "<h3 style='margin:0;font-size:15px;font-weight:bold;margin-right:10px;'>"+pos["label"]+"</h3>";
      }
      else {
        rs = pos["label"];
      }
      var html = "<div style='width:270px'>" + titleHTML + "<br/><div style='font-size:13px;'>"+pos["info"]+"<br/>信息来源：<a href='"+pos["source"]["url"]+"' target='blank_'>"+pos["source"]["label"]+"</a></div></div>";
      if(typeof searchResult[rs] != "undefined" && searchResult[rs] != null) {
        var tabtitle = "路况信息";
        if(pos["cata"] != "ROAD"){
          tabtitle = "灾害警报";
        }
        var tab1 = new GInfoWindowTab(tabtitle, html);
        /*searchResult[res][0].html.style.width = "270px";
        searchResult[res][0].html.style.fontSize = "13px";*/
        var html = document.createElement("div");
        html.style.cssText = "width:270px;font-size:13px;";
        var str = "";
        for(var i = 0; i < searchResult[rs][0].length; i++) {
          var news = searchResult[rs][0][i];
          var title = news.titleNoFormatting;
          var pub = news.publisher;
          var pubtime = news.publishedDate;
          var date = new Date(pubtime);
          date = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 ";
          var url = news.unescapedUrl;
          var tit = title;
          if(tit.length > 18) {
            tit = tit.substr(0, 18) + "...";
          }
          str += "<a target='_blank' title=\"" + title + "\" href=\"" + url + "\">" + tit + "</a><br/>";
          str += "<p style='color:#6F6F6F'>" + pub + " " + date + "</p>";
        }
        str += "<a href=\"" + searchResult[rs][1] + "\" target=\"_blank\" style='float:right;padding-top:5px;'>更多新闻</a>";
        html.innerHTML = str;
        var tab2 = new GInfoWindowTab("相关新闻", html);
        marker.openInfoWindowTabs([tab1, tab2]);
      }
      else {
        marker.openInfoWindowHtml(html);
      }
      
      
    }

    function setSearchResult(ele) {
      if(searchNews.results == null || searchNews.results.length == 0 || searchNews.gwsUrl == null){
        searchResult[ele] == null;
      }
      else {
        searchResult[ele] = [searchNews.results, searchNews.gwsUrl];
      }
      if(searchStack.length != 0) {
        var searchEle = searchStack.shift();
        searchNews.setNoHtmlGeneration();
        searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
        if(searchEle[1] == "ROAD") {
         searchNews.execute(searchEle[0] + " 春运");
        }
        else {
          searchNews.execute(searchEle[0]);
        }
      }
    }
    function geocodeWCallback(node, name, iconurl){
      return function(response){
        if (response && response.Placemark && response.Status.code == 200) {
          place = response.Placemark[0];
          var latlng = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
          var marker = addWMarker(latlng, iconurl);
          node.city.lat = place.Point.coordinates[1];
          node.city.lng = place.Point.coordinates[0];
          addWListener(marker, node);
          //TODO add response to Server
          rpcProxy.setWGeo(name, place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
        } else {
          //TODO remove node?
          node.style.textDecoration = "line-through";
        }

        if(geostack.length == 0) {
          resizeMap();
          return;
        }
        var geostackele = geostack.shift();
        geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
      }
    }
    function geocodeCallback(node, name){
      return function(response){
        if (response && response.Placemark && response.Status.code == 200) {
          place = response.Placemark[0];
          node.pos.latlng = [place.Point.coordinates[1], place.Point.coordinates[0]];
          var marker = addMarker(node.pos, node.iconurl);
          addListener(node, marker);
          
          //TODO add response to Server
          rpcProxy.setGeo(name, place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
        } else {
          //TODO remove node?
          node.style.textDecoration = "line-through";
        }

        if(geostack.length == 0) {
          resizeMap();
          return;
        }
        var geostackele = geostack.shift();
        geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
      }
    }
    function dateChange(date) {
      var month = date.getMonth() + 1;
      if(month < 10) {
        month = "0" + month;
      }
      var dat = date.getDate();
      if(dat < 10) {
        dat = "0" + dat;
      }
      if(cur.date == "" + date.getFullYear() + month + dat) return;
      $("datetxt").innerHTML = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
      cur.page = 0;
      
      cur.date = "" + date.getFullYear() + month + dat;
      rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
    }
    
    function onAfterChange() {
      if(cur.date == null) return;
      cur.page = 0;
      searchStack = [];
      searchResult = [];
      if($("category").value == "0") {
        cur.category = "ROAD";
      }
      else {
        cur.category = "ALARM";
      }
      rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
    }
    
    function onOptionsChange(){
      //cur.region = dom.region.options[dom.region.selectedIndex].value;
      //cur.category = dom.category.options[dom.category.selectedIndex].value;
      //cur.date = dom.date.options[dom.date.selectedIndex].value;
      cur.page = 0;
      cur.date = null;
      cur.region = null;
      searchStack = [];
      searchResult = [];
      $("regionsbut").innerHTML = "全部";
      $("datetxt").innerHTML = "全部";
      $("regionslist").style.display = "none";
      if($("category").value == "1") {
        rpcProxy.getWeather(0, cur.region);
        $("datediv").style.display = "none";
      }
      else {
        if($("category").value == "0") {
          cur.category = "ROAD";
        }
        else {
          cur.category = "ALARM";
        }
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
        $("datediv").style.display = "";
      }
    }
    function onPageChange(isWeather){
      return function() {
        searchStack = [];
        searchResult = [];
        cur.page = this.id.substr(1);
        if(isWeather){
          rpcProxy.getWeather(cur.page, cur.region);
        }
        else {
          rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
        }
      }
    }
    $("prePage").onclick = function(){
      if(cur.page == 0) return;
      cur.page--;
      if($("category").value == "1") {
        rpcProxy.getWeather(cur.page, cur.region);
      }
      else {
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
      }
    }
    $("nextPage").onclick = function(){
      if(cur.page == totalPage - 1) return;
      cur.page++;
      if($("category").value == "1") {
        rpcProxy.getWeather(cur.page, cur.region);
      }
      else {
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
      }
    }
    var setSearchWe = function() {
      var abc = 1;
    };
    var initAjaxSearch = function() {
      searchNews = new google.search.NewsSearch();
      searchNews.setRestriction(google.search.Search.RESTRICT_EXTENDED_ARGS, { "ned" : "cn"});

      if(searchStack.length != 0) {
        searchEle = searchStack.shift();
        searchNews.setNoHtmlGeneration();
        searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
        if(searchEle[1] == "ROAD") {
          searchNews.execute(searchEle[0] + " 春运");
        }
        else {
          searchNews.execute(searchEle[0]);
        }
      }
    };
    return {
      init : function(){
        map = new GMap2(); 
        rpcProxy.getOptions();
        makeShareButton();
        google.load("search", "1.0", {'language': 'zh_CN'});
	      google.setOnLoadCallback(initAjaxSearch, true);
      },
      importWeather: function(data){
        var result = data.result;
        cached.points = [];
        map.clearOverlays();
        dom.container.innerHTML = "";
        for(var i = 0; i < result.length; i++) {
          var city = result[i];
          //if(result[i].current.length == 0 || result[i].forecast.length == 0) continue;
          var title = city.city + "天气情况";
          
          var curcon = city.condition;
          var iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/qing.png';
          if(curcon.indexOf('雨') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/xiaoyu.png';
          }
          else if(curcon.indexOf('云') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/duoyun.png';
          }
          else if(curcon.indexOf('雪') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/xiaoxue.png';
          }
          else if(curcon.indexOf("阴") != -1) {
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/yin.png';
          }
          var node = addWNode(title, iconurl);
          node.city = city;
          if(city.lat != null && city.lng != null){
            var marker = addWMarker(new GLatLng(city.lat, city.lng), iconurl);
            addWListener(marker, node);
          } else {
            geostack.push([city.city, node]);
          }        
        }
        if(geostack.length != 0){
          var geostackele = geostack.shift();
          geocoder.getLocations(geostackele[0], geocodeWCallback(geostackele[1], geostackele[0], iconurl));
        }
        else {
          if(result.length != 0) {
            resizeMap();
          }
        }
        if(result.length != 0) {
          totalPage = data.total;
          $("prePage").style.display = "";
          $("nextPage").style.display = "";
          dom.page.innerHTML = "";
          for(var i = 0; i < totalPage; i++){
            var pageLink = $n("span", "page-link", dom.page, {id:"p"+i});
            pageLink.innerHTML = i+1;
            pageLink.onclick = onPageChange(true);
            dom.page.appendChild(pageLink);
            if(i == data.page){
              pageLink.className = "active-page";
            }
          }
        }
        else {
          $("listContainer").innerHTML = "<div style='text-align:center;'>没有查询到相关信息。</div>";
          $("prePage").style.display = "none";
          $("nextPage").style.display = "none";
        }
      },
      importResult : function(result){
        map.clearOverlays();
        cached.points = [];
        dom.container.innerHTML = "";
        var data = result.result;
        var cata = result.cata;
        searchResult = [];
        for (var i = 0, pos; pos = data[i]; i++) {
          var node = addNode(pos);
          node.pos = pos;
          pos["cata"] = cata;
          pos.latlng = pos.latlng || cached.latlng[pos.region];
          var re = /^(.*)(省|自治区)/;
          var res = re.exec(pos.region);
          if(res == null) {
            re = /^(.*)市/;
            res = re.exec(pos.region);
          }
          res = res[0];
          if(typeof searchResult[res] == "undefined") {
            if(cata == "ROAD") {
              searchStack.push([res, cata]);
            }
            else {
              searchStack.push([pos['label'], cata]);
            }
          }
          var iconurl = "";
          if(cata == "ROAD") {
            iconurl = "http://ditu.google.cn/intl/zh-CN_cn/images/truck-disabled.png"
          }
          else {
            var label = data[i]["label"];
            iconurl = "/html/blue.png";
            if(label.indexOf("黄色") != -1) {
              iconurl = "http://ditu.google.com/intl/zh-CN_cn/images/yellow.png";
            }
            else if(label.indexOf("橙色") != -1) {
              iconurl = "http://ditu.google.com/intl/zh-CN_cn/images/orange.png";
            }
            else if(label.indexOf("红色") != -1) {
              iconurl = "http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/caution.white.png";
            }
          }
          if(pos.latlng){
            var marker = addMarker(pos, iconurl);
            addListener(node, marker);
          } else {
            node.iconurl = iconurl
            geostack.push([pos.region, node]);
            
          }
        }
        if(geostack.length != 0){
          var geostackele = geostack.shift();
          geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
        }
        else {
          if(data.length != 0) {
            resizeMap();
          }
        }
        if(searchStack.length != 0 && searchNews != null) {
          var searchEle = searchStack.shift();
          searchNews.setNoHtmlGeneration();
          searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
          if(searchEle[1] == "ROAD") {
            searchNews.execute(searchEle[0] + " 春运");
          }
          else {
            searchNews.execute(searchEle[0]);
          }
        }
        if(data.length != 0) {
          totalPage = result.total;
          $("prePage").style.display = "";
          $("nextPage").style.display = "";
          dom.page.innerHTML = "";
          for(var i = 0; i < totalPage; i++){
            var pageLink = $n("span", "page-link", dom.page, {id:"p"+i});
            pageLink.innerHTML = i+1;
            pageLink.onclick = onPageChange();
            dom.page.appendChild(pageLink);
            if(i == result.page){
              pageLink.className = "active-page";
            }
          }
        }
        else {
          $("listContainer").innerHTML = "<div style='text-align:center;'>没有查询到相关信息。</div>";
          $("prePage").style.display = "none";
          $("nextPage").style.display = "none";
        }
      },
      initOptions : function(options){
/*        cached.region = options.region;
        cached.category = options.category;
        //region
        dom.region.removeChild(dom.region.firstChild);
        for (var i in cached.region) {
          var option = new Option(cached.region[i].name, cached.region[i].id);
          dom.region.options[dom.region.options.length] = option;
          
        }
        dom.region.onchange = onOptionsChange;
        //category
        dom.category.removeChild(dom.category.firstChild);
        for(var i in cached.category){
          var option = new Option(cached.category[i].name, cached.category[i].id);
          dom.category.options[dom.category.options.length] = option;
        }
        dom.category.onchange = onOptionsChange;
        //date
        dom.date.removeChild(dom.date.firstChild);
        var now = new Date();
        var month = now.getMonth();
        var year = now.getFullYear();
        var day = now.getDate();
        for (var i = day; i > 0; i--) {
          var label = new Date(year, month, i).toLocaleDateString();
          var d = i < 10 ? "0" + i : i;
          var option = new Option(label, year + "0" + (month + 1) + "" + d);
          dom.date.options[dom.date.options.length] = option;
        }
        if (month > 0) {
          month--;
          for (var i = 31; i > 0; i--) {
            var label = new Date(year, month, i).toLocaleDateString();
            var d = i < 10 ? "0" + i : i;
            var option = new Option(label, year + "0" + (month + 1) + "" + d);
            dom.date.options[dom.date.options.length] = option;
          }
        }
        dom.date.onchange = onOptionsChange;*/
        regions[1] = options.wearegion;
        cur.category = "ROAD";
        regions[0] = options.roadregion;
        regions[2] = options.alarmregion;

        $("category").value = "0";
        $("category").onchange = onOptionsChange;
        $("viewafter").onchange = onAfterChange;
        new Calendar_("POPUP", "datebut", dateChange, {
          'align': 'left'
        });
        
        $("viewall").onclick = function() {
          cur.date = null;
          if($("datetxt").innerHTML == "全部") return;
          $("datetxt").innerHTML = "全部";
          rpcProxy.getSearch(cur.region, cur.category, null, 0);         
        };
        $("regionsbut").onclick = function() {
          var list = $("regionslist");
          if(list.style.display != "none") {
            list.style.display = "none";
            return;
          }
          var reg = null;
          if($("category").value == "0") {
            reg = regions[0];
          }
          else if($("category").value == "1") {
            reg = regions[1];
          }
          else {  
            reg = regions[2];
          }
          var quanbu = $n("div");
          quanbu.innerHTML = "全部";
          quanbu.style.cssText = 'margin:5px;cursor:pointer;';
          list.innerHTML = "";
          list.appendChild(quanbu);
          quanbu.onclick = function() {
            $("regionslist").style.display = "none";
            if($("regionsbut").innerHTML == this.innerHTML) return;
            cur.region = null;
            if($("category").value == "1") {
              rpcProxy.getWeather(cur.page, cur.region);
            }
            else {
              rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
            }
            $("regionsbut").innerHTML = this.innerHTML;
          }
          for(var i = 0; i < reg.length; i++) {
            var item = $n("div");
            item.innerHTML = reg[i];
            item.style.cssText = 'margin:2px 5px;cursor:pointer;float:left';
            item.onclick = function() {
              $("regionslist").style.display = "none";
              if($("regionsbut").innerHTML == this.innerHTML) return;
              cur.region = this.innerHTML;
              $("regionsbut").innerHTML = this.innerHTML;
              if($("category").value == "1") {
                rpcProxy.getWeather(cur.page, cur.region);
              }
              else {
                rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
              }
            }
            list.appendChild(item);
          }
          var clr = $n("div");
          clr.style.cssText = "clear:both;line-height:0;height:0;font-size:0";
          list.appendChild(clr);
          list.style.display = "";
          _IG_AdjustIFrameHeight();
        };
        onOptionsChange();
      }
    }
  })();
  window['ChunyunMap'] = {
    'init' : mgr.init,
    'callback_options' : rpcProxy.getOptionsCallback,
    'callback_search' : rpcProxy.getSearchCallback,
    'callback_weather': rpcProxy.getWeatherCallback
  }
})();
_IG_RegisterOnloadHandler(ChunyunMap.init);
